package com.ktjy.filter;

import com.ktjy.dto.LoginUser;
import com.ktjy.utils.Constants;
import com.ktjy.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtTokenFilter extends OncePerRequestFilter {
    @Value("${token.header}")
    private String header;
    @Autowired
    JWTUtil jWTUtil;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //登录用户信息
        String token = request.getHeader(header);
        if (token!=null && !token.isEmpty() && token.startsWith("Bearer "))
        {
            //去掉前缀Bearer
            token = token.replace("Bearer ", "");
            //解析token
            Claims claims = null;
            try {
                claims = jWTUtil.parseToken(token);
                //从redis获取用户信息
                LoginUser loginUser= (LoginUser)
                        redisTemplate.opsForValue().get(Constants.LOGIN_USER +claims.get("username"));
                if(loginUser!=null && SecurityContextHolder.getContext().getAuthentication()==null){
                    //将用户信息存储到security的上下文
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        filterChain.doFilter(request,response);
    }
}
